package com.qiu.wbpostman.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import com.qiu.wbpostman.common.PMF;
import javax.jdo.Query;

public class BaseDao<T> {
	private Class<T> persistentClass;
	private PersistenceManager pm;

	public BaseDao(Class<T> class1) {
		pm = PMF.get().getPersistenceManager();
		this.persistentClass = class1;
	}

	/**
	 * 持久化一个对象
	 * 
	 * @param t
	 */
	public void creat(T t) {
		try {
			pm.makePersistent(t);
		} finally {
			pm.close();
		}
	}

	/**
	 * 根据主键id取得一个对象
	 * 
	 * @param c
	 * @param id
	 * @return
	 */
	public T getObjectById(Class c, Long id) {
		try {
			T t = (T) pm.getObjectById(c, id);
			return t;
		} finally {
			pm.close();
		}
	}

	/**
	 * 根据主键更新一个对象
	 * 
	 * @param t
	 * @param id
	 */
	public void update(T t, long id) {
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			T t1 = (T) pm.getObjectById(t.getClass(), id);
			t1 = t;
			pm.makePersistent(t1);
			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
	}

	/**
	 * 删除一个对象
	 * 
	 * @param t
	 */
	public void delete(T t) {
		try {
			pm.deletePersistent(t);
		} finally {
			pm.close();
		}
	}

	/**
	 * 查询多个对象
	 * 
	 * @param t
	 * @param jdoql
	 * @return
	 */
	public List<T> findList(T t, String jdoql) {
		try {
			Query query = pm.newQuery(t.getClass(), jdoql);
			List<T> list = (List<T>) query.execute();
			return list;
		} finally {
			pm.close();
		}
	}

	/**
	 * 返回指定条数的数据
	 * 
	 * @param t
	 * @param jdoql
	 * @param start
	 * @param end
	 * @return
	 */
	public List<T> findList(T t, String jdoql, long start, long end) {
		try {
			Query query = pm.newQuery(t.getClass(), jdoql);
			query.setRange(start, end);
			List<T> list = (List<T>) query.execute();
			return list;
		} finally {
			pm.close();
		}
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}

	public void setPersistentClass(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public PersistenceManager getPm() {
		return pm;
	}

	public void setPm(PersistenceManager pm) {
		this.pm = pm;
	}

}
